package com.dzu.easy;

/**
 * @author ZhaoDong
 * @date 2022/11/10 11:12
 * @description 476. 数字的补数
 */
public class Test476 {
    public static void main(String[] args) {
        System.out.println(findComplement(5));
    }
    public static int findComplement2(int num) {
        int s = -1;
        for (int i = 31; i >= 0; i--) {
            if (((num >> i) & 1) != 0) {
                s = i;
                break;
            }
        }
        int ans = 0;
        for (int i = 0; i < s; i++) {
            if (((num >> i) & 1) == 0) ans |= (1 << i);
        }
        return ans;
    }
    public static int findComplement(int num) {
        int res = 0;
        int count = 0;
        while (num > 0) {
            res |= ((num & 1) ^ 1) << count;
            count++;
            num >>>= 1;
        }
        int res2 = 0;
        count = 0;
        while (res > 0) {
            res2 |= (res & 1)<< count ;
            res >>>= 1;
            count++;
        }
        return res2;
    }

}
